package com.libinshen.wxpay.quartz.controller;

import com.libinshen.wxpay.common.annotation.ControllerEndpoint;
import com.libinshen.wxpay.common.vo.CommonResult;
import com.libinshen.wxpay.quartz.entity.Job;
import com.libinshen.wxpay.quartz.entity.QueryRequest;
import com.libinshen.wxpay.quartz.entity.Strings;
import com.libinshen.wxpay.quartz.service.IJobService;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@Validated
@RestController
@RequestMapping("job")
public class JobController {

    private IJobService jobService;

    @GetMapping
    public CommonResult jobList(QueryRequest request, Job job) {
        return CommonResult.ok().data("0", jobService.findJobs(request, job));
    }

    @GetMapping("cron/check")
    public boolean checkCron(String cron) {
        try {
            return CronExpression.isValidExpression(cron);
        } catch (Exception e) {
            return false;
        }
    }

    @PostMapping
    public CommonResult addJob(@Valid Job job) {
        jobService.createJob(job);
        return CommonResult.ok();
    }

    @GetMapping("delete/{jobIds}")
    public CommonResult deleteJob(@NotBlank(message = "{required}") @PathVariable String jobIds) {
        jobService.deleteJobs(StringUtils.split(jobIds, Strings.COMMA));
        return CommonResult.ok();
    }

    @PostMapping("update")
    @ControllerEndpoint(operation = "修改定时任务", exceptionMessage = "修改定时任务失败")
    public CommonResult updateJob(@Valid Job job) {
        jobService.updateJob(job);
        return CommonResult.ok();
    }

    @GetMapping("run/{jobIds}")
    public CommonResult runJob(@NotBlank(message = "{required}") @PathVariable String jobIds) {
        jobService.run(jobIds);
        return CommonResult.ok();
    }

    @GetMapping("pause/{jobIds}")
    public CommonResult pauseJob(@NotBlank(message = "{required}") @PathVariable String jobIds) {
        jobService.pause(jobIds);
        return CommonResult.ok();
    }

    @GetMapping("resume/{jobIds}")
    public CommonResult resumeJob(@NotBlank(message = "{required}") @PathVariable String jobIds) {
        jobService.resume(jobIds);
        return CommonResult.ok();
    }
}
